<template>
  <container>
    <div class="app-container">
      <el-row :gutter="20">
        <!--表单分类数据-->
        <el-col :span="4" :xs="24">
          <div class="head-container">
            <el-input
              v-model="name"
              placeholder="请输入分类名称"
              clearable
              size="small"
              prefix-icon="el-icon-search"
              style="margin-bottom: 20px"
            />
          </div>
          <div class="head-container">
            <el-tree
              :data="treeOptions"
              :props="defaultProps"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              :render-content="renderContent"
              ref="tree"
              highlight-current
              @node-click="handleNodeClick"
            />
          </div>
        </el-col>
        <el-col :span="20" :xs="24">
          <el-form ref="form" size="small" :model="searchForm" align="right">
            <el-row>
              <el-col :span="8">
                <el-form-item label="应用编号" label-width="80px" prop="username">
                  <el-input v-model="searchForm.formId" prefix-icon="el-icon-search" placeholder="请输入表单id"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="应用名称" label-width="80px" prop="name">
                  <el-input v-model="searchForm.name" prefix-icon="el-icon-search" placeholder="请输入表单名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="btn-container">
                <el-button icon="el-icon-search" type="primary" size="small"  @click="search">查询</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="search('reset')">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
          <div class="btn-container">
            <el-button type="primary" size="small" plain icon="el-icon-plus"  @click="openDialog('add')"
            >新增</el-button>
          </div>
          <el-table row-key="id" v-loading="listLoading" :data="list"  style="width: 100%">
            <el-table-column v-for="item in tableColumns" :key="item.prop" v-bind="item">
              <template slot-scope="scope">
                <div v-if="item.prop === 'index'">{{ scope.$index + 1 }}</div>
                <div v-if="item.prop=='selection'">
                  <el-table-column type="selection" width="50"></el-table-column>
                </div>
                <div v-if="item.prop=='icon'">
                  <icon-svg :name="scope.row.icon" />
                </div>
                <div v-else-if="item.prop === 'applicationType'">
                  <dict-tag :options="optionStatus" :value="scope.row.applicationType"/>
                </div>
                <div v-else-if="item.prop === 'operation'" class="operation-btn">
                  <el-button icon="el-icon-edit" size="mini" type="text" @click="handlerEdit(scope.row)">编辑</el-button>
                  <el-popconfirm title="您确定要删除吗？"
                                 @confirm="deleteById(scope.row)">
                    <el-button icon="el-icon-delete" slot="reference" size="mini" type="text" class="btn-danger">删除</el-button>
                  </el-popconfirm>
                </div>
                <div v-else>{{ scope.row[item.prop] }}</div>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="searchForm.pageNum"
            :limit.sync="searchForm.pageSize"
            @pagination="getList"
          />
        </el-col>
      </el-row>
    </div>
    <el-drawer
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogVisible"
      :close-on-press-escape="false"
      :wrapperClosable="false"
      destroy-on-close
      size="70%"
    >
      <div class="drawer-content" style="height: 100%">
        <el-steps :active="activeSteps-1" finish-status="success" simple >
          <el-step title="1.选择类型"></el-step>
          <el-step title="2.显示字段"></el-step>
          <el-step title="3.设置条件"></el-step>
          <el-step title="4.设置权限"></el-step>
          <el-step title="5.应用发布"></el-step>
        </el-steps>
        <div v-if="activeSteps-1==0" style="height: 100%">
          <el-form style="width: 98%;padding-top: 20px;height: 100%"
                   ref="applicationTypeForm"
                   :model="applicationTypeForm"
                   label-width="100px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="应用类型:" prop="applicationType">
                  <el-radio-group v-model="applicationTypeForm.applicationType">
                    <el-radio label="0">表单应用</el-radio>
                    <el-radio label="1" disabled>SQL应用</el-radio>
                    <el-radio label="2" disabled>接口应用</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="applicationTypeForm.applicationType=='0'">
                <el-form-item label="表单模版:" prop="id">
                  <treeselect
                    v-model="applicationTypeForm.id"
                    :options="formTree"
                    :normalizer="normalizer"
                    @select="setSelectedTree"
                    placeholder="选择表单模版"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="applicationTypeForm.applicationType=='1'">
                <el-form-item label="数据源:" prop="dataSource">
                  <el-select v-model="dataSource" placeholder="请选择">
                    <el-option value="local" label="local"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item prop="form_data_table">
                  <span slot="label">
                    <el-tooltip content="select 需要显示到列表中的列，隐藏列可在第二步设置是否显示" placement="top">
                      <i class="el-icon-question"></i>
                      </el-tooltip>
                      SQL语句:
                  </span>
                  <el-input v-model="applicationTypeForm.form_data_table" rows="5"
                            type="textarea" placeholder=""></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24" v-if="applicationTypeForm.applicationType=='2'">
                <el-form-item prop="form_data_table">
                  <span slot="label">
                    <el-tooltip content="接口请求类型必须为POST,返回结果必须包含在result消息体中" placement="top">
                      <i class="el-icon-question"></i>
                      </el-tooltip>
                      接口地址:
                  </span>
                  <el-input v-model="applicationTypeForm.form_data_table" rows="5"
                            type="textarea" placeholder=""></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
        <div v-show="activeSteps-1==1" style="height: 100%">
          <el-table
            ref="settingKeysData"
            :data="formKeysData"
            row-key="id"
            style="width: 100%"
            @selection-change="handleSelectionChange"
            >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="id" align="center" label="字段编码" ></el-table-column>
            <el-table-column prop="label" align="center" label="字段名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.label"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="compType" align="center" label="字段类型" >
              <template slot-scope="scope">
                <dict-tag :options="formItems" :value="scope.row.compType"/>
              </template>
            </el-table-column>
            <el-table-column prop="options" v-if="false" />
            <el-table-column prop="dataType" v-if="false" />
            <el-table-column prop="action" v-if="false" />
          </el-table>
        </div>
        <div v-show="activeSteps-1==2" style="height: 100%">
          <el-table
            :data="formKeysData"
            row-key="id"
            ref="settingSearchKey"
            style="width: 100%"
            @selection-change="handleSelectionKeys"
          >
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="id" align="center" label="字段编码" ></el-table-column>
            <el-table-column prop="label" align="center" label="字段名称">
              <template slot-scope="scope">
                <el-input v-model="scope.row.label"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="compType" align="center" label="字段类型" >
              <template slot-scope="scope">
                <dict-tag :options="formItems" :value="scope.row.compType"/>
              </template>
            </el-table-column>
            <el-table-column prop="options" v-if="false" />
            <el-table-column prop="dataType" v-if="false" />
            <el-table-column prop="action" v-if="false" />
          </el-table>
        </div>
        <div v-show="activeSteps-1==3" style="height: 100%">
          <el-form>
            <el-table
              :data="btnDatas"
              row-key="id"
              ref="btnDataRef"
              style="width: 100%;"
            >
              <el-table-column prop="btnNo" align="center" label="按钮编码" ></el-table-column>
              <el-table-column prop="btnName"  align="center" label="按钮名称">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.btnName"></el-input>
                </template>
              </el-table-column>
              <el-table-column prop="state" align="center" label="按钮状态" >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.state" placeholder="请选择">
                    <el-option value="0" label="禁用"></el-option>
                    <el-option value="1" label="启用"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="roles" align="center" label="角色权限" >
                <template slot-scope="scope">
                  <el-select
                    v-model="scope.row.roles"
                    multiple
                    collapse-tags
                    style="margin-left: 20px;"
                    placeholder="请选择">
                    <el-option
                      v-for="item in roles"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </template>
              </el-table-column>
            </el-table>
          </el-form>

          <el-form style="padding-top: 20px">
            <el-button
              type="success"
              size="mini"
              icon="el-icon-plus"
              @click="addtable"
            >
              添加
            </el-button>
            <el-button
              type="warning"
              size="mini"
              icon="el-icon-share"
              @click="qingchutable"
            >
              清空
            </el-button>
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click="deltable"
            >
              删除
            </el-button>

            <el-table
              :data="btnParams"
              class="table1"
              @selection-change="handleDetailSelectionChange"
              :row-class-name="rowClassName"
              ref="btnParamsTable"
            >
              <el-table-column
                type="selection"
                width="30"
                align="center"
              />
              <el-table-column
                type="index"
                label="序号"
                width="50"
              > </el-table-column>

              <el-table-column
                label="按钮编码"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.btnNo"></el-input>
                </template>
              </el-table-column>

              <el-table-column
                label="按钮名称"
              >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.btnName"></el-input>
                </template>
              </el-table-column>

              <el-table-column
                label="操作类型"
              >
                <template slot-scope="scope">
                  <el-select v-model="scope.row.type" placeholder="请选择">
                    <el-option value="0" label="关联表单"></el-option>
                    <el-option value="1" label="执行接口"></el-option>
                    <el-option value="2" label="打开链接"></el-option>
                  </el-select>
                </template>
              </el-table-column>

              <el-table-column
                label="操作内容"
              >
                <template slot-scope="scope">
                  <treeselect
                    v-if="scope.row.type=='0'"
                    v-model="scope.row.doc"
                    :options="formTree"
                    :appendToBody="true"
                    z-index="9999"
                    :normalizer="normalizer"
                    @select="setSelectedTree"
                    placeholder="选择表单模版"
                  />
                  <el-input v-else="scope.row.type!='0'" v-model="scope.row.doc"></el-input>

                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
        <div v-show="activeSteps-1==4" style="height: 100%">
          <el-form style="width: 98%" ref="menuForm" :model="menuForm"  label-width="100px">
            <el-row>
              <el-col :span="24">
                <el-form-item label="上级菜单">
                  <treeselect
                    v-model="menuForm.parentId"
                    :options="treeOptions"
                    :normalizer="normalizerMenu"
                    placeholder="选择上级菜单"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="菜单图标" prop="icon">
                  <el-popover
                    placement="bottom-start"
                    width="460"
                    trigger="click"
                    @show="$refs['iconSelect'].reset()"
                  >
                    <iconSelect ref="iconSelect" @selected="selected" />
                    <el-input slot="reference" v-model="menuForm.icon" placeholder="点击选择图标" readonly>
                      <icon-svg
                        v-if="menuForm.icon"
                        slot="prefix"
                        :name="menuForm.icon"
                        class="el-input__icon"
                        style="height: 32px;width: 16px;"
                      />
                      <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                    </el-input>
                  </el-popover>
                </el-form-item>
                <el-col :span="12">
                  <el-form-item label="菜单名称" prop="menuName">
                    <el-input v-model="menuForm.menuName" placeholder="请输入菜单名称" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="显示排序" prop="orderNum">
                    <el-input-number v-model="menuForm.orderNum" controls-position="right" :min="0" />
                  </el-form-item>
                </el-col>
              </el-col>
              <el-col :span="12">
                <el-form-item label="路由地址" prop="path">
                  <el-input v-model="menuForm.path" placeholder="请输入路由地址" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="组件路径" prop="component">
                  <el-input v-model="menuForm.component" placeholder="请输入组件路径" readonly/>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="菜单说明" prop="remark">
                  <el-input v-model="menuForm.remark" type="textarea" placeholder=""></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <div class="drawer-footer">
        <el-button type="primary" v-if="activeSteps>1" @click="skipTo('up')"> 上一步 </el-button>
        <el-button type="primary" v-if="activeSteps<6&&activeSteps!=5" @click="skipTo('next')"> 下一步 </el-button>
        <el-button type="primary" v-if="activeSteps==5" @click="handlerSubmit()"> 确定 </el-button>
        <el-button @click="handlerColse()"> 取消 </el-button>
      </div>
    </el-drawer>
  </container>
</template>

<script>
import SelectTree from '@/components/selectTree/index.vue';
import dictTag from "@/components/dictTag";
import {rolesList} from '@/api/orgm/orgm';
import Pagination from '@/components/Pagination';
import { titleMap } from '@/const';
import {
  formApplicationList,
  getFormTree,
  setFormMenu,
  getFormAppSetting,
  depeteFormMenu,
  getFormTreeByAdd
} from '@/api/process/processFrom';
import { getMenuList} from "@/api/system/menu";
import {handleTree,dataJson} from "@/utils/comm";
import iconSvg from "@/components/icon-svg";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import iconSelect from "@/components/iconSelect";
import {mapGetters} from "vuex";

export default {
  name: 'fappSetting',
  components: { Pagination,SelectTree,iconSvg,Treeselect,iconSelect,dictTag },
  data() {
    return {
      titleMap,
      //菜单树
      treeOptions:[],
      //表单树
      formTree:[],
      formTreeCopy:[],
      //步骤
      activeSteps:1,
      name:'',
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      list: [],
      total: 0,
      //角色列表
      roles:[],
      listLoading: false,
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        id: '',
        name: '',
        formSort: ''
      },
      dialogVisible: false,
      dialogStatus: 'add',
      applicationTypeForm: {
        applicationType:"",
        id:undefined
      },
      menuForm:{
        component:'form/application/index'
      },
      dataSource:'local',
      //选中的表单json
      mapJson:"",
      //表单字段
      formKeysData:[],
      //已选显示字段
      selectData:[],
      //查询字段
      searchKeys:[],
      btnDatas:[
        {
          btnNo:"add",
          btnName:"新增",
          state:"1",
          roles:undefined
        },
        {
          btnNo:"edit",
          btnName:"编辑",
          state:"1",
          roles:undefined
        },
        {
          btnNo:"delete",
          btnName:"删除",
          state:"1",
          roles:undefined
        },
        {
          btnNo:"exp",
          btnName:"导出",
          state:"1",
          roles:undefined
        }
      ],
      //已设置的查询字段
      settingKeys:[],
      btnParams:[],
      btnCheckedDetail:[],
    };
  },
  computed:{
    ...mapGetters('store/formMenu',[
      'formItems',
      'optionStatus',
      'tableColumns'
    ]),
  },
  created() {
    this.getList();
    this.getSelectData();
    this.getFormTreeData();
    this.getRoles();
  },
  watch: {
    // 根据名称筛选部门树
    name(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    // 获取
    getList() {
      this.listLoading = true;
      formApplicationList(this.searchForm).then((res) => {
        if (res.code === 200) {
          this.list = res.rows;
          this.total = res.total;
        } else {
          this.$message.error(`获取列表失败`);
        }
        this.listLoading = false;
      });
    },
    //查询
    search(type) {
      if (type === 'reset') {
        this.$refs.form.resetFields();
      }
      this.searchForm.page = 1;
      this.getList();
    },
    // 获取下拉框数据
    getSelectData() {
      const params= {
          menuName: undefined,
          visible: undefined
        };
      getMenuList(params).then(response => {
        this.treeOptions = handleTree(response.result, "menuId");
      });
    },
    getRoles(){
      const params={
        name:'',
          page: 0,
          pagesize: 0
      };
      rolesList(params).then(res=>{
        if(res.error=="200"){
          this.roles = res.result;
        }
        else{
          this.$message.error("获取失败");
        }
      })
    },
    getFormTreeData(){
      getFormTree().then(res=>{
        this.formTree=handleTree(res.result, "id","formSort");
        this.formTreeCopy=this.formTree;
      });
    },
    normalizerMenu(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.menuId,
        label: node.menuName,
        children: node.children
      };
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    setSelectedTree(node, selectedOptions){
      if(node.form_json==""||node.form_json==undefined){
        this.$message.warning("请选择具体的表单")
        return;
      }
      this.mapJson=node.form_json;
      this.formKeysData=dataJson(JSON.parse(this.mapJson));
    },
    //设置显示的列
    handleSelectionChange(row){
      this.selectData=row;
    },
    //设置查询列
    handleSelectionKeys(row){
      this.searchKeys=row;
    },
    //编辑
    async handlerEdit(row) {
      getFormAppSetting(row.id).then(res=>{
        if(res.error=="200"){
          //表单类型
          this.applicationTypeForm.applicationType=res.result.applicationType;
          if(res.result.applicationType=="0"){
            //表单id
            this.applicationTypeForm.id=res.result.id;
          }
          else if(res.result.applicationType=="1"){
            const dataDoc=res.result.form_data_table.split(":");
            this.applicationTypeForm.form_data_table=dataDoc[1];
            this.dataSource=dataDoc[0];
          }
          else if(res.result.applicationType=="2"){
            this.applicationTypeForm.form_data_table=res.result.form_data_table;
          }
          //按钮
          const btns=JSON.parse(res.result.btns);
          //系统按钮
          this.btnDatas=btns.toolbar;
          //自定义按钮
          this.btnParams=btns.selfbar;
          //表单字段
          this.formKeysData=dataJson(JSON.parse(res.result.form_json));
          //显示的字段
          this.selectData=JSON.parse(res.result.cols);
          //查询字段
          this.settingKeys=JSON.parse(res.result.searchRules);
          //菜单信息
          this.menuForm=res.result.menu;
          //设置已选的显示字段、查询字段
          this.$nextTick(()=>{
            this.selectData.forEach(s=>{
              this.formKeysData.forEach(item=>{
                if(s.id==item.id){
                  this.$refs.settingKeysData.toggleRowSelection(item,true);
                }
              })
            });
            this.settingKeys.forEach(s=>{
              this.formKeysData.forEach(item=>{
                if(s.id==item.id){
                  this.$refs.settingSearchKey.toggleRowSelection(item,true);
                }
              })
            });
          });
          this.dialogVisible = true;
        }
      });

    },
    openDialog(){
      getFormTreeByAdd().then(res=>{
        this.formTree=handleTree(res.result, "id","formSort");
        this.dialogVisible = true;
      });
    },
    skipTo(type){
      if(this.formKeysData.length<=0&&this.applicationTypeForm.applicationType=="0"){
        this.$message.warning("请选择表单");
        return;
      }
      if(type=='up'){
        if(this.activeSteps==1){
          return;
        }
        this.activeSteps--;
      }
      else if(type=='next'){
        if(this.activeSteps==1){
          if(this.applicationTypeForm.applicationType=="1"){
            let sql=this.applicationTypeForm.form_data_table;
            sql=sql.replace("select","");
            sql=sql.replace("SELECT","");

          }
        }
        if(this.activeSteps==2){
          if(this.selectData.length<=0){
            this.$message.warning("请选择列表显示的列");
            return;
          }
        }
        this.activeSteps++;
      }
    },
    handlerSubmit() {
      let btns={};
      btns.toolbar=this.$refs.btnDataRef.data;
      btns.selfbar=this.$refs.btnParamsTable.data;
      let formEntity=this.applicationTypeForm;
      formEntity.cols=JSON.stringify(this.selectData);
      formEntity.searchRules=JSON.stringify(this.searchKeys);
      formEntity.btns=JSON.stringify(btns);
      formEntity.menu=this.menuForm;
      if(this.applicationTypeForm.applicationType=="1")
        formEntity.form_data_table=this.dataSource+":"+this.applicationTypeForm.form_data_table;
      setFormMenu(formEntity).then(res=>{
        if(res.error=="200"){
          this.$message.success("发布成功");
          this.handlerColse();
          this.getList();
        }
        else{
          this.$message.warning(res.msg);
        }
      })
    },
    async deleteById(row) {
      const res = await depeteFormMenu(row);
      if (res.error === 200) {
        this.$message.success(`删除成功`);
        this.search('reset');
      } else {
        this.$message.error(`删除失败`);
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.menuName.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.searchForm.formSort = data.menuId;
      this.search('search');
    },
    /** 显示label **/
    renderContent(h,{node}){
      return (
        <span class="custom-tree-node">
          <span title={node.label}>{node.label}</span>
        </span>
      );
    },
    handlerColse(){
      this.dialogVisible=false;
      this.activeSteps=1;
      this.reset();
    },
    reset(){
      this.applicationTypeForm={
        applicationType:"",
        id:undefined,
        form_data_table:""
      };
      this.dataSource="";
      this.mapJson="";
      this.formTree=this.formTreeCopy;
    },
    //添加自定义按钮行
    addtable() {
      if (this.btnParams == undefined) {
        this.btnParams = new Array();
      }
      let obj = {
        btnNo: '',
        btnName: null,
        type: undefined,
        doc:undefined
      };

      this.btnParams.push(obj);
    },
    //清空自定义按钮列表
    qingchutable() {
      this.btnParams = [];
    },
    //删除选中的自定义按钮
    deltable() {
      if (this.btnCheckedDetail.length == 0) {
        this.$alert("请先选择要删除的数据", "提示", {
          confirmButtonText: "确定",
        });
      } else {
        this.btnParams.splice(this.btnCheckedDetail[0].index - 1, 1);
      }
    },
    //动态生成参数列表的index
    rowClassName({ row, rowIndex }) {
      row.index = rowIndex + 1;
    },
    //选中参数行
    handleDetailSelectionChange(selection) {
      if (selection.length > 1) {         //删除一行
        this.$refs.btnParamsTable.clearSelection();//清空用户的选择
        this.$refs.btnParamsTable.toggleRowSelection(selection.pop());//切换某一行的选中状态
      } else {
        this.btnCheckedDetail = selection;
      }
    },
    // 选择图标
    selected(name) {
      this.menuForm.icon = name;
    },
  }
};
</script>
